#!/usr/bin/env bash
# vim: fdm=marker fmr=[[[,]]] cms=\ #%s

OS=$(uname | tr 'A-Z' 'a-z')
PHPCGI=php-cgi
BIN_PATH=
RUNNER=soar

usage()
{ #[[[
    echo "Usage: svrctl start | stop | status"
} #]]]

running()
{ #[[[
    killall -0 $PHPCGI 2>/dev/null
} #]]]

command()
{ #[[[
    local option="$1"
    case "$option" in
    "start")
        running
        if (( $? == 0 ))
        then
            echo "$PHPCGI is running, no operation..."
            return 1
        fi
        cd $BIN_PATH
        if [[ $USER == 'root' ]]
        then
            sudo -b -u $RUNNER ./run-php-cgi.sh
        else
            ./run-php-cgi.sh &
        fi
        sleep 1
        running
        if (( $? != 0 ))
        then
            echo "$PHPCGI start fail, check"
            return 1
        fi
        echo "$PHPCGI start succeed"
        ;;
    "stop")
        running
        if (( $? == 0 ))
        then
            killall $PHPCGI
            sleep 1
            running
            if (( $? == 0 ))
            then
                echo "$PHPCGI stop fail, check"
                return 1
            fi
            echo "$PHPCGI stop succeed"
        else
            echo "$PHPCGI not started"
        fi
        ;;
    "status")
        running
        if (( $? == 0 ))
        then
            case $OS in
            linux)
                ps -ef|grep -v grep|awk '$8 == "'$PHPCGI'" { print }'
                ;;
            freebsd)
                ps aux|grep -v grep|awk '$11 == "'$PHPCGI'" { print }'
                ;;
            esac
        else
            echo "$PHPCGI not started"
        fi
        ;;
    *)
        usage
        ;;
    esac
} #]]]#

interact()
{ #[[[
    local option
    read -p "\
Options:
    1) start
    2) stop
    s) status
Choose: " option
    case $option in
    1) command start ;;
    2) command stop ;;
    s) command status ;;
    *) command ? ;;
    esac
} #]]]

main()
{ #[[[
    local argv=$1

    BIN_PATH=$(dirname $0)
    if [[ ${BIN_PATH:0:1} != '/' ]]
    then
        BIN_PATH=$PWD/$BIN_PATH
    fi

    if [[ -z $argv ]]
    then
        interact
    else
        command "$argv"
    fi
} #]]]

main $@
exit $?
